package m.framework.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import m.framework.controller.BaseController;
import m.framework.controller.CurrentUser;
import m.framework.controller.UserHolder;
import m.framework.dao.selector.Query;
import m.framework.service.BaseService;
import m.framework.utils.StringUtil;
import m.permission.model.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author ming
 * @date 2014年2月19日下午6:04:40
 */
public class UserInfoInterceptor implements HandlerInterceptor {
	private static Logger log = LoggerFactory.getLogger(UserInfoInterceptor.class);

	public static final String SEESION_ID = "sessionId";
	// 不需要验证用户的页面
	private List<String> ignors = new ArrayList();
	// seesionid生成器
	private SessionIdCreator idCreator = new SessionIdCreator();
	// 保存当前线程用户的类
	private UserHolder holder = new BaseController();

	public UserInfoInterceptor() {
		ignors.add("/frame/login.json");
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		for (String s : ignors) {
			if (s.equals(request.getRequestURI())) {
				return true;
			}
		}

		Cookie[] ck = request.getCookies();
		if (ck == null) {
			return toLogin(request,response);
		}
		for (Cookie c : ck) {
			log.debug("cookies--" + c.getName() + ":" + c.getValue());
			if (c.getName().equals(SEESION_ID)) {
				String userCode = null;
				
				try{
					userCode=idCreator.toUserCode(c.getValue());
				}catch(Exception ex){
					log.warn("将sessionId转为userCode的时出错:"+ex.getMessage(),ex);
					Cookie deleSessionId=new Cookie(SEESION_ID,"");
					deleSessionId.setPath("/");
					response.addCookie(deleSessionId);
					return toLogin(request,response);
				}
				
				if (StringUtil.isEmpty(userCode)) {
					return toLogin(request,response);
				}
				CurrentUser user = getUser(userCode);
				if (user == null) {
					log.warn("用户不存在:" + userCode);
					return toLogin(request,response);
				}
				holder.setUser(user);
				log.debug("设置当前线程用户为" + user.getUserCode());
				return true;
			}
		}
		log.warn("未找到名称为" + SEESION_ID + "的cookie");
		return toLogin(request,response);
	}

	private boolean toLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
		log.debug("用户非法访问"+request.getRequestURI()+"被丢回首页");
		Cookie cok=new Cookie("message","unauthorized");
		cok.setPath("/");
		response.addCookie(cok);
		response.sendRedirect("/");
		return false;
	}

	private CurrentUser getUser(String userCode) {
		Query q = Query.forClass(User.class);
		q.eq("userCode", userCode);
		List list = BaseService.getDefault().query(q);
		if (list.size() > 0) {
			return (CurrentUser) list.get(0);
		}
		return null;

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		CurrentUser user = holder.getUser();
		Cookie ck = new Cookie(SEESION_ID, null);
		ck.setPath("/");
		if (user != null) {
			ck.setValue(idCreator.toSessionId(user.getUserCode()));
		} else {
			log.debug("当前线程不存在用户清除cookie");
		}
		response.addCookie(ck);
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
